package org.bing.engine.jmx;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.management.remote.JMXConnector;


import sun.jvmstat.monitor.HostIdentifier;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;
import sun.management.ConnectorAddressLink;

public class HotspotVirtualMachineManager implements VirtualMachineManager {

    public List<LocalVirtualMachine> getAllLocalVirtualMachine() {
        try {
            return doLookup();
        } catch (Throwable t) {
            // TODO impl logging
            return new ArrayList<LocalVirtualMachine>();
        }
    }

    @SuppressWarnings("rawtypes")
    private List<LocalVirtualMachine> doLookup() throws Exception {
        MonitoredHost host = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));
        Set vms = host.activeVms();
        List<LocalVirtualMachine> list = new ArrayList<LocalVirtualMachine>();
        for (Object vmid : vms) {
            if (vmid instanceof Integer) {
                int pid = ((Integer) vmid).intValue();
                String name = vmid.toString(); // default to pid if name not available
                boolean attachable = false;
                String address = null;
                try {
                    MonitoredVm mvm = host.getMonitoredVm(new VmIdentifier(name));
                    // use the command line as the display name
                    name = MonitoredVmUtil.commandLine(mvm);
                    attachable = MonitoredVmUtil.isAttachable(mvm);
                    address = ConnectorAddressLink.importFrom(pid);
                    mvm.detach(); 
                } catch (Exception x) {
                    // ignore
                }
                list.add(new LocalVirtualMachine(pid, name, attachable, address));
            }
        }
        return list;
    }

    public static void main(String[] args) throws Exception {
        VirtualMachineManager vmm = new HotspotVirtualMachineManager();
        MBeanTracer tracer = new MBeanTracer();
        JmxConnectorManager connector = new JmxConnectorManager();
        List<LocalVirtualMachine> list = vmm.getAllLocalVirtualMachine();
        for (LocalVirtualMachine lvm : list) {
            // System.out.println(lvm.getDisplayName() + "   >>>\n" + lvm.getCommandLine());
            System.out.println(lvm.getVmid());
            JMXConnector conn = connector.getJMXConnector(lvm);
            if (conn != null) {
                System.out.println(">>> ");
                tracer.trace(conn);
            }
        }
        System.out.println(" ---------------------------------------------- \n");
    }
}
